<template>
  <el-card>
    <el-button icon="ele-Plus" type="primary" @click="addTradeItem"
      >添加</el-button
    >
    <el-table :data="paginationAtt.records" border style="width: 100%">
      <el-table-column label="序号" width="180" type="index" />
      <el-table-column label="名称" prop="tmName"> </el-table-column>
      <el-table-column label="产品logo">
        <template #="{ row }"> <img :src="row.logoUrl" width="100" /></template>
      </el-table-column>
      <el-table-column label="操作">
        <template #="{ row }">
          <myButton
            type="warning"
            icon="ele-Edit"
            @click="updateRow(row)"
            :permission="`btn.Trademark.update`"
            >修改</myButton
          >
          <!-- <myButton type="warning" icon="ele-Edit" @click="updateRow(row)" :permission=""
            >修改</myButton
          > -->
          <!-- //if -->
          <!-- <el-button
            type="danger"
            icon="ele-Delete"
            @click="delTradeItem(row.id)"
            v-if="userInfo.buttons.includes(`btn.Trademark.remove`)"
            >删除</el-button
          > -->
          <!-- // 指令-->
          <el-button
            type="danger"
            icon="ele-Delete"
            @click="delTradeItem(row.id)"
            v-permission="`btn.Trademark.remove`"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="paginationAtt.current"
      v-model:page-size="paginationAtt.size"
      :total="paginationAtt.total"
      layout="prev,pager,next,jumper,->,sizes,total"
      :page-sizes="[5, 10, 15, 20]"
    />

    <el-dialog
      v-model="dialogVisible"
      :title="formData.id ? `更新品牌-${formData.tmName}` : '添加品牌'"
    >
      <el-form :rules="formDataRules" :model="formData" ref="formRef">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请输入品牌的名称"
            v-model="formData.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- v-model:file-list="fileList" -->
          <el-upload
            class="uploader"
            :action="uploadUrl"
            :on-success="onSuccessHandler"
            :show-file-list="false"
            :before-upload="beforeUploadHandler"
          >
            <img
              :src="formData.logoUrl"
              alt=""
              v-if="formData.logoUrl"
              class="thumb"
            />
            <el-icon class="uploader-icon" v-else
              ><ele-Plus></ele-Plus
            ></el-icon>
            <template #tip>
              <p>
                上传的图片必须是{{ settings.uploadFileExt.join("、") }}格式
                小于{{ settings.uploadFileLimitSize }}kb
              </p>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="default" @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click="updateAndAddTradeItem"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </el-card>
</template>
<script lang="ts">
import { defineComponent, nextTick } from "vue";
import type { IResTradeType } from "@/api/api";
import settings from "@/settings";

export default defineComponent({
  name: "Trademark",
});
</script>
<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from "vue";
import {
  reqTradeMarkList,
  reqTradeSave,
  reqUpdateTrademark,
  reqDelTradeItem,
} from "@/api/trademark";
import type { recordType } from "@/api/api";
import {
  type UploadUserFile,
  type UploadFile,
  type UploadFiles,
  type FormRules,
  type UploadRawFile,
  ElMessage,
  ElMessageBox,
} from "element-plus";
// const tradeRecordList = ref<recordType[]>([]);
import { setUserStore } from "@/stores/user";
import { storeToRefs } from "pinia";
const userStore = setUserStore();
const { userInfo } = storeToRefs(userStore);
//分页属性
let paginationAtt = ref<IResTradeType>({
  records: [],
  total: 0,
  size: 5,
  current: 1,
  searchCount: true,
  pages: 0,
});
//获取表单实例
const formRef = ref();
// console.log(paginationAtt);
//数据渲染
async function getTradeRecordList() {
  try {
    const res = await reqTradeMarkList(
      paginationAtt.value.current,
      paginationAtt.value.size
    );
    paginationAtt.value = res;
  } catch (e) {}
}
// getTradeRecordList();
//封装监听函数
function mywatch(value: () => number) {
  return watch(
    value,
    () => {
      getTradeRecordList();
    },
    { immediate: true }
  );
}
// getter监听
mywatch(() => paginationAtt.value.current); //如果是paginationAtt是响应式数据或者.value也可以 return是将函数转为getter函数 watch能监听get函数
mywatch(() => paginationAtt.value.current);
//表单验证规则
const formDataRules: FormRules = {
  tmName: { required: true, min: 1, message: "不能为空" },
  logoUrl: {
    required: true,
    validator(rule: any, value: string, callback) {
      if (value.trim().startsWith("http")) {
        callback();
      } else {
        callback(new Error("地址不正确"));
      }
    },
  },
};

//上传模块
const dialogVisible = ref(false);
const uploadUrl = `${import.meta.env.VITE_API_URL}/product/upload`;
// const fileList = ref<UploadUserFile[]>([]);
// const fileInfo = computed(() => {
//   if (
//     fileList.value.length > 0 &&
//     fileList.value[fileList.value.length - 1].response
//   ) {
//     return (
//       fileList.value[fileList.value.length - 1].response as { data: string }
//     ).data;
//   } else {
//     return "";
//   }
// });
// const fileInfo = ref<string>("");
// const formData = reactive({
//   tmName: "",
//   logoUrl: "",
// });

//初始化提交数据
const formData = ref<Partial<Pick<recordType, "id">> & Omit<recordType, "id">>({
  tmName: "",
  logoUrl: "",
});
//图片预览地址
function onSuccessHandler(
  response: { data: string },
  UploadFile: UploadFile,
  UploadFiles: UploadFiles
) {
  formData.value.logoUrl = response.data;
}
//文件规则
const beforeUploadHandler = (rawFile: UploadRawFile) => {
  console.log("rawFile", rawFile);

  if (!settings.uploadFileExt.includes(rawFile.type.slice(6))) {
    ElMessage.error("不允许上传该类型的文件");
    return false;
  }
  if (rawFile.size / 1024 > settings.uploadFileLimitSize) {
    ElMessage.error("超出容量");
    return false;
  }
};
//取消校验
const cancelForm = async () => {
  await formRef.value.clearValidate();
};
//添加
const addTradeItem = () => {
  dialogVisible.value = true;
  formData.value = {
    tmName: "",
    logoUrl: "",
  };
  // nextTick(async () => {
  //   await cancelForm();
  // });
  setTimeout(() => {
     cancelForm();
  });
};
//取消
const cancelDialog = () => {
  dialogVisible.value = false;
};
//统一表单校验

// console.log(formRef.value);

//成功添加或更新函数

const updateAndAddTradeItem = async () => {
  console.log("formData");
  try {
    //新增
    const tradeInfo = formData.value.id ? "修改" : "新增";
    await formRef.value.validate();
    // console.log("formData.value.id", formData.value.id);
    if (paginationAtt.value.total % paginationAtt.value.size != 0) {
      paginationAtt.value.current = paginationAtt.value.pages;
    } else {
      paginationAtt.value.current = paginationAtt.value.pages + 1;
    }

    if (formData.value.id) {
      // console.log("1");

      //修改
      await reqUpdateTrademark(formData.value as recordType);
    } else {
      await reqTradeSave(formData.value);
    }

    ElMessage.success(`${tradeInfo}ok`);
    await getTradeRecordList();
    dialogVisible.value = false;
  } catch (e) {
    console.log(e);

    ElMessage.error(`{tradeInfo}出错`);
  }
};
//更新按钮
const updateRow = (row: recordType) => {
  console.log("row", row);
  formData.value = { ...row };
  dialogVisible.value = true;
};
//删除
const delTradeItem = async (id: number) => {
  try {
    await ElMessageBox.confirm("Are you ok", "是否删除", { type: "warning" });
    await reqDelTradeItem(id);
    ElMessage.success("删除成功");
    if (paginationAtt.value.records.length == 1)
      paginationAtt.value.current = paginationAtt.value.current - 1;
    await getTradeRecordList();
  } catch (e) {
    // console.log("e", e);
    ElMessage.warning("取消删除");
  }
};
</script>
<style scoped>
.uploader .thumb {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
